import type {
  CoupleProfile,
  DateRecord,
  Gift,
  Anniversary,
  Album,
  Photo,
  Message,
  WishItem,
} from '@/types/couple'
import dayjs from 'dayjs'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  coupleService,
  messageService,
  anniversaryService,
  dateRecordService,
  giftService,
  wishlistService,
  albumService,
} from '@/services/supabase'

export const useSupabaseCoupleStore = defineStore('supabaseCouple', () => {
  // 状态
  const profile = ref<CoupleProfile | null>(null)
  const dateRecords = ref<DateRecord[]>([])
  const gifts = ref<Gift[]>([])
  const anniversaries = ref<Anniversary[]>([])
  const albums = ref<Album[]>([])
  const messages = ref<Message[]>([])
  const wishlist = ref<WishItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 当前情侣档案 ID (硬编码)
  const currentCoupleId = ref<string>('58202fec-7c38-42be-9a3b-de121c4a18f1')

  // 计算属性：恋爱天数
  const daysInLove = computed(() => {
    if (!profile.value?.relationshipStart)
      return 0
    return dayjs().diff(dayjs(profile.value.relationshipStart), 'day')
  })

  // 计算属性：即将到来的纪念日
  const upcomingAnniversaries = computed(() => {
    const today = dayjs()
    const upcoming = anniversaries.value
      .map((anniversary) => {
        const thisYear = today.year()
        let anniversaryDate = dayjs(anniversary.date).year(thisYear)

        if (anniversaryDate.isBefore(today, 'day')) {
          anniversaryDate = anniversaryDate.year(thisYear + 1)
        }

        return {
          ...anniversary,
          nextDate: anniversaryDate.format('YYYY-MM-DD'),
          daysLeft: anniversaryDate.diff(today, 'day'),
        }
      })
      .sort((a, b) => a.daysLeft - b.daysLeft)

    return upcoming
  })

  // 计算属性：总照片数
  const totalPhotos = computed(() => {
    return albums.value.reduce((total, album) => total + album.photos.length, 0)
  })

  // 错误处理函数
  function handleError(err: any, message: string) {
    console.error(message, err)
    error.value = err.message || message
  }

  // 初始化档案数据
  async function initProfile() {
    if (profile.value)
      return // Prevent re-loading

    try {
      loading.value = true
      error.value = null

      const profileData = await coupleService.getById(currentCoupleId.value)
      if (profileData) {
        profile.value = profileData
        await loadAllData()
      }
      else {
        throw new Error('找不到指定的情侣档案')
      }
    }
    catch (err) {
      handleError(err, '加载档案失败')
    }
    finally {
      loading.value = false
    }
  }

  // 加载所有数据
  async function loadAllData() {
    if (!currentCoupleId.value)
      return

    try {
      const [
        anniversariesData,
        dateRecordsData,
        giftsData,
        albumsData,
        // messagesData,
        wishlistData,
      ] = await Promise.all([
        anniversaryService.getByCouple(currentCoupleId.value),
        dateRecordService.getByCouple(currentCoupleId.value),
        giftService.getByCouple(currentCoupleId.value),
        albumService.getAll(),
        // messageService.getByCouple(currentCoupleId.value),
        wishlistService.getByCouple(currentCoupleId.value),
      ])

      anniversaries.value = anniversariesData
      dateRecords.value = dateRecordsData
      gifts.value = giftsData
      albums.value = albumsData
      // messages.value = messagesData
      wishlist.value = wishlistData
    }
    catch (err) {
      handleError(err, '加载数据失败')
    }
  }

  // 更新档案
  async function updateProfile(data: Partial<CoupleProfile>) {
    if (!profile.value)
      return
    try {
      loading.value = true
      const updatedProfile = await coupleService.update(profile.value.id, data)
      profile.value = updatedProfile
    }
    catch (err) {
      handleError(err, '更新档案失败')
    }
    finally {
      loading.value = false
    }
  }

  // 添加消息
  async function addMessage(message: Omit<Message, 'id' | 'createdAt'>) {
    if (!currentCoupleId.value)
      return
    try {
      const newMessage = await messageService.create(currentCoupleId.value, message)
      messages.value.unshift(newMessage)
      return newMessage
    }
    catch (err) {
      handleError(err, '发送消息失败')
    }
  }

  // 添加纪念日
  async function addAnniversary(anniversary: Omit<Anniversary, 'id' | 'createdAt'>) {
    if (!currentCoupleId.value)
      return
    try {
      const newAnniversary = await anniversaryService.create(currentCoupleId.value, anniversary)
      anniversaries.value.push(newAnniversary)
      return newAnniversary
    }
    catch (err) {
      handleError(err, '添加纪念日失败')
    }
  }

  // 更新纪念日
  async function updateAnniversary(id: string, updates: Partial<Anniversary>) {
    if (!currentCoupleId.value)
      return
    try {
      const updated = await anniversaryService.update(id, updates)
      const index = anniversaries.value.findIndex(a => a.id === id)
      if (index !== -1)
        anniversaries.value[index] = { ...anniversaries.value[index], ...updated }
      return updated
    }
    catch (err) {
      handleError(err, '更新纪念日失败')
    }
  }

  // 删除纪念日
  async function removeAnniversary(id: string) {
    if (!currentCoupleId.value)
      return
    try {
      await anniversaryService.delete(id)
      const index = anniversaries.value.findIndex(a => a.id === id)
      if (index !== -1)
        anniversaries.value.splice(index, 1)
    }
    catch (err) {
      handleError(err, '删除纪念日失败')
    }
  }

  // 约会记录
  async function addDateRecord(record: Omit<DateRecord, 'id' | 'createdAt'>) {
    if (!currentCoupleId.value)
      return
    try {
      const newRecord = await dateRecordService.create(currentCoupleId.value, record)
      dateRecords.value.unshift(newRecord)
      return newRecord
    }
    catch (err) {
      handleError(err, '添加约会记录失败')
    }
  }

  async function updateDateRecord(id: string, data: Partial<DateRecord>) {
    if (!currentCoupleId.value)
      return
    try {
      const updatedRecord = await dateRecordService.update(id, data)
      const index = dateRecords.value.findIndex(r => r.id === id)
      if (index !== -1) {
        dateRecords.value[index] = { ...dateRecords.value[index], ...updatedRecord }
      }
      return updatedRecord
    }
    catch (err) {
      handleError(err, '更新约会记录失败')
    }
  }

  async function removeDateRecord(id: string) {
    if (!currentCoupleId.value)
      return
    try {
      await dateRecordService.delete(id)
      const index = dateRecords.value.findIndex(r => r.id === id)
      if (index !== -1) {
        dateRecords.value.splice(index, 1)
      }
    }
    catch (err) {
      handleError(err, '删除约会记录失败')
    }
  }

  // 礼物
  async function addGift(gift: Omit<Gift, 'id' | 'createdAt'>) {
    if (!currentCoupleId.value)
      return
    try {
      const newGift = await giftService.create(currentCoupleId.value, gift)
      gifts.value.unshift(newGift)
      return newGift
    }
    catch (err) {
      handleError(err, '添加礼物失败')
    }
  }

  async function updateGift(id: string, data: Partial<Gift>) {
    if (!currentCoupleId.value)
      return
    try {
      const updatedGift = await giftService.update(id, data)
      const index = gifts.value.findIndex(g => g.id === id)
      if (index !== -1) {
        gifts.value[index] = { ...gifts.value[index], ...updatedGift }
      }
      return updatedGift
    }
    catch (err) {
      handleError(err, '更新礼物失败')
    }
  }

  async function removeGift(id: string) {
    if (!currentCoupleId.value)
      return
    try {
      await giftService.delete(id)
      const index = gifts.value.findIndex(g => g.id === id)
      if (index !== -1) {
        gifts.value.splice(index, 1)
      }
    }
    catch (err) {
      handleError(err, '删除礼物失败')
    }
  }

  // 愿望
  async function addWish(wish: Omit<WishItem, 'id' | 'createdAt' | 'updatedAt'>) {
    if (!currentCoupleId.value)
      return
    try {
      const newWish = await wishlistService.create(currentCoupleId.value, wish)
      wishlist.value.unshift(newWish)
      return newWish
    }
    catch (err) {
      handleError(err, '添加愿望失败')
    }
  }

  async function updateWish(id: string, data: Partial<WishItem>) {
    if (!currentCoupleId.value)
      return
    try {
      const updatedWish = await wishlistService.update(id, data)
      const index = wishlist.value.findIndex(w => w.id === id)
      if (index !== -1) {
        wishlist.value[index] = { ...wishlist.value[index], ...updatedWish }
      }
      return updatedWish
    }
    catch (err) {
      handleError(err, '更新愿望失败')
    }
  }

  async function removeWish(id: string) {
    if (!currentCoupleId.value)
      return
    try {
      await wishlistService.delete(id)
      const index = wishlist.value.findIndex(w => w.id === id)
      if (index !== -1) {
        wishlist.value.splice(index, 1)
      }
    }
    catch (err) {
      handleError(err, '删除愿望失败')
    }
  }

  // 相册
  async function addAlbum(album: Omit<Album, 'id' | 'createdAt' | 'updatedAt' | 'photos'>) {
    try {
      const newAlbum = await albumService.create(album)
      albums.value.unshift(newAlbum)
      return newAlbum
    }
    catch (err) {
      handleError(err, '创建相册失败')
    }
  }

  async function updateAlbum(albumId: string, data: Partial<Album>) {
    try {
      const updatedAlbum = await albumService.update(albumId, data)
      const index = albums.value.findIndex(a => a.id === albumId)
      if (index !== -1) {
        albums.value[index] = { ...albums.value[index], ...updatedAlbum }
      }
      return updatedAlbum
    }
    catch (err) {
      handleError(err, '更新相册失败')
    }
  }

  async function removeAlbum(albumId: string) {
    try {
      await albumService.delete(albumId)
      const index = albums.value.findIndex(a => a.id === albumId)
      if (index !== -1) {
        albums.value.splice(index, 1)
      }
    }
    catch (err) {
      handleError(err, '删除相册失败')
    }
  }

  async function addPhotoToAlbum(albumId: string, photo: Omit<Photo, 'id' | 'uploadedAt'>) {
    try {
      const newPhoto = await albumService.addPhoto(albumId, photo)
      const album = albums.value.find(a => a.id === albumId)
      if (album) {
        album.photos.push(newPhoto)
      }
      return newPhoto
    }
    catch (err) {
      handleError(err, '添加照片失败')
    }
  }

  async function removePhotoFromAlbum(albumId: string, photoId: string) {
    try {
      await albumService.removePhoto(photoId)
      const album = albums.value.find(a => a.id === albumId)
      if (album) {
        const index = album.photos.findIndex(p => p.id === photoId)
        if (index !== -1) {
          album.photos.splice(index, 1)
        }
      }
    }
    catch (err) {
      handleError(err, '删除照片失败')
    }
  }

  // 仅用于初次设置的测试函数
  async function createDefaultProfileForTesting() {
    try {
      loading.value = true
      const defaultProfile = {
        user1: {
          name: 'Az',
          avatar: '/static/images/he.png',
          birthday: '1998-02-07',
          gender: 'male' as const,
        },
        user2: {
          name: 'sasa',
          avatar: '/static/images/she.png',
          birthday: '1999-09-21',
          gender: 'female' as const,
        },
        relationshipStart: '2023-02-14',
        status: 'dating' as const,
        story: '我们在一个美好的春日相遇。',
      }

      const newProfile = await coupleService.create(defaultProfile)
      return newProfile
    }
    catch (err) {
      handleError(err, '创建默认档案失败')
      return null
    }
    finally {
      loading.value = false
    }
  }

  return {
    // 状态
    profile,
    dateRecords,
    gifts,
    anniversaries,
    albums,
    messages,
    wishlist,
    loading,
    error,
    currentCoupleId,

    // 计算属性
    daysInLove,
    upcomingAnniversaries,
    totalPhotos,

    // 方法
    initProfile,
    updateProfile,
    addMessage,
    addAnniversary,
    updateAnniversary,
    removeAnniversary,
    addDateRecord,
    updateDateRecord,
    removeDateRecord,
    addGift,
    updateGift,
    removeGift,
    addWish,
    updateWish,
    removeWish,
    loadAllData,
    addAlbum,
    updateAlbum,
    removeAlbum,
    addPhotoToAlbum,
    removePhotoFromAlbum,
    createDefaultProfileForTesting,
  }
})
